
if (window.loadFirebugConsole) window.loadFirebugConsole();

(function () {

    var queryField;
    var searchButton;
    var peopleResultList;
    var pageResultList;
    var currentQuery;

    var initialize = function () {
    
        queryField = document.getElementById("queryfield");
        searchButton = document.getElementById("searchbutton");

        personResultList = new ResultList("People", document.getElementById("personresults"));
        pageResultList = new ResultList("Other Search Results", document.getElementById("pageresults"));

        queryField.disabled = false;
        searchButton.disabled = false;
        queryField.focus();

        var initialQuery = getQueryFromLocation();
        if (initialQuery) {
            startQuery(initialQuery);
        }
        
        setInterval(function () {
            var query = getQueryFromLocation();
            if (query && query != currentQuery) {
                startQuery(query);
            }
        }, 50);

        var startQueryFromField = function () {
            var newQuery = queryField.value;
            window.location.hash = '#'+escape(newQuery);
            //startQuery(newQuery);
        };
        
        queryField.addEventListener("keypress", function (evt) {
            if (evt.keyCode == 13) {
                startQueryFromField();
                return false;
            }
        }, false);
        searchButton.addEventListener("click", function (evt) {
            startQueryFromField();
        }, true);
    };
    
    var startQuery = function (query) {
        currentQuery = query;
        queryField.value = query;
        personResultList.clearResults();
        pageResultList.clearResults();
        
        if (! query) {
            return;
        }
        
        // Keep a local reference to the query so that if results come back
        // out of turn we can just keep the current results.
        var thisQuery = query;

        var callback = function (result) {
            if (thisQuery != currentQuery) return;

            var people = result.people;
            for (var i = 0; i < people.length; i++) {
                var person = people[i];
                var personResult = new PersonResult(person);
                personResultList.addResult(personResult);
            }

            var pages = result.pages;
            for (var i = 0; i < pages.length; i++) {
                var page = pages[i];
                var pageResult = new PageResult(page);
                pageResultList.addResult(pageResult);
            }

        };

        PeopleSearch.findPeople(query, callback);

    };

    /* PersonResult */
    var PersonResult = function (person) {
        this.person = person;
        var rootElem = this.domElem = document.createElement("div");
        rootElem.className = "personresult";
        
        rootElem.appendChild(makePhotoHolder(person.getPhotoURLs(), 100, 100));
        
        var detailsElem = document.createElement("div");
        detailsElem.className = "personresultdetails";
        rootElem.appendChild(detailsElem);
        
        var nameElem = document.createElement("div");
        nameElem.className = "personresultname";
        var otherNames = person.getDisplayNames();
        var displayName = otherNames.shift();
        if (displayName) {
            nameElem.appendChild(document.createTextNode(displayName));
        }
        else {
            nameElem.innerHTML = "(name unknown)";
            nameElem.className += " nameless";
        }
        detailsElem.appendChild(nameElem);
        
        if (otherNames.length) {
            var akaElem = document.createElement("div");
            akaElem.className = "personresultaka";
            akaElem.appendChild(document.createTextNode("aka "+otherNames.join(", ")));
            detailsElem.appendChild(akaElem);
        }
        
        var nodesContainerElem = document.createElement("div");
        nodesContainerElem.className = "personresultnodescontainer collapsed";
        
        var nodesExpanderElem = document.createElement("div");
        nodesExpanderElem.className = "expander";
        nodesExpanderElem.innerHTML = "(toggle expanded view)";
        nodesExpanderElem.title = "Toggle Expanded View";
        var expanded = false;
        nodesExpanderElem.addEventListener("click", function (evt) {
            if (expanded) {
                nodesContainerElem.className = "personresultnodescontainer collapsed";
                expanded = false;
            }
            else {
                nodesContainerElem.className = "personresultnodescontainer expanded";
                expanded = true;
            }
        }, true);
        nodesContainerElem.appendChild(nodesExpanderElem);
        
        var nodesElem = document.createElement("ul");
        nodesElem.className = "personresultnodes";
        
        
        var nodes = person.getNodes();
        for (var ni = 0; ni < nodes.length; ni++) {
            var node = nodes[ni];
            if (node.hasAssociatedIdentNode()) continue;
            var nodeElem = document.createElement("li");
            var nodeLinkElem = document.createElement("a");
            var domain = node.getSGNDomain();
            var username = node.getUsername();
            var titleText = username + (domain ? " @ "+domain : "");
            
            if (domain == "mboxsha1") continue;
            
            nodeLinkElem.href = node.getPrimaryURL();
            nodeLinkElem.setAttribute("title", titleText);
            nodeLinkElem.appendChild(document.createTextNode(username));
            nodeLinkElem.style.backgroundImage = 'url('+node.getIconURL()+')';
            
            nodeElem.appendChild(nodeLinkElem);
            nodesElem.appendChild(nodeElem);
        }
        
        nodesContainerElem.appendChild(nodesElem);
        detailsElem.appendChild(nodesContainerElem);

        var clearElem = document.createElement("div");
        clearElem.style.clear = 'both';
        detailsElem.appendChild(clearElem);
        
    };
    PersonResult.prototype = {};
    PersonResult.prototype.getDOMElement = function () {
        return this.domElem;
    };

    /* PageResult */
    var PageResult = function (page) {
        this.page = page;
        var rootElem = this.domElem = document.createElement("div");
        rootElem.className = "pageresult";
        
        var headingElem = document.createElement("div");
        headingElem.className = "pageresultheading";
        rootElem.appendChild(headingElem);
        
        var linkElem = document.createElement("a");
        linkElem.href = page.searchResult.url;
        linkElem.innerHTML = page.searchResult.title;
        headingElem.appendChild(linkElem);
        
        var bodyElem = document.createElement("p");
        bodyElem.innerHTML = page.searchResult.content;
        rootElem.appendChild(bodyElem);
        
        var footerElem = document.createElement("div");
        footerElem.className = "pageresultfooter";
        footerElem.innerHTML = page.searchResult.visibleUrl + (page.searchResult.cacheUrl ? ' - ' : '');
        if (page.searchResult.cacheUrl) {
            var cacheLinkElem = document.createElement("a");
            cacheLinkElem.href = page.searchResult.cacheUrl;
            cacheLinkElem.innerHTML = "Cached";
            footerElem.appendChild(cacheLinkElem);
        }
        rootElem.appendChild(footerElem);
    };
    PageResult.prototype = {};
    PageResult.prototype.getDOMElement = function () {
        return this.domElem;
    };

    /* ResultList */
    var ResultList = function (titleHTML, elem) {
        this.titleHTML = titleHTML;
        this.elem = elem;
        this.items = [];
        this.listElem = null;
        this.clearResults();
    };
    ResultList.prototype = {};
    
    ResultList.prototype.clearResults = function () {
        this.listElem = null;
        this.elem.style.display = 'none';
        this.elem.innerHTML = "";
        this.items = [];
    };
    
    ResultList.prototype.addResult = function (result) {
        if (! this.listElem) {
            // Do initial setup of the element
            var heading = document.createElement("h2");
            heading.innerHTML = this.titleHTML;
            var list = document.createElement("ul");
            this.elem.appendChild(heading);
            this.elem.appendChild(list);
            list.className = "resultslist";
            this.elem.style.display = '';
            this.listElem = list;
        }
        
        this.items.push(result);
        
        var itemElem = result.getDOMElement();
        
        var li = document.createElement("li");
        li.appendChild(itemElem);
        this.listElem.appendChild(li);
    };

    function getQueryFromLocation() {
        if (window.location.hash) {
            return decodeURIComponent(window.location.hash.substr(1));
        }
        else {
            return null;
        }
    }
    
    function makePhotoHolder(urls, size) {
        var ret = document.createElement("div");
        ret.className = "photoholder";
        ret.style.width = size+"px";
        ret.style.height = size+"px";
        ret.style.overflow = 'hidden';
        ret.style.position = "relative";
        
        var imageElems = [];
        for (var i = 0; i < urls.length; i++) {
            var imageElem = document.createElement("img");
            imageElem.src = urls[i];
            imageElem.alt = "";
            imageElem.onload = function (evt) {
                var image = evt.target;
                
                // Scale it to fit in our box, and center it.
                
                var sourceWidth = image.width;
                var sourceHeight = image.height;
                var maxSize = size;
                var ourWidth = null;
                var ourHeight = null;
                var aspect = sourceWidth / sourceHeight;

                if (sourceWidth <= maxSize && sourceHeight <= maxSize) {
                    // No resizing required!
                    ourWidth = sourceWidth;
                    ourHeight = sourceHeight;
                }
                else if (sourceWidth >= sourceHeight) {
                    // The image is wider than it is tall, or it's square
                    ourWidth = maxSize;
                    ourHeight = maxSize / aspect;
                }
                else {
                    // The image is taller than it is wide
                    ourWidth = maxSize * aspect;
                    ourHeight = maxSize;
                }

                image.setAttribute("width", ourWidth);
                image.setAttribute("height", ourHeight);

                // Now how much do we need to offset them to center them in the box?
                var x = (maxSize / 2) - (ourWidth / 2);
                var y = (maxSize / 2) - (ourHeight / 2);
                image.style.position = "absolute";
                image.style.left = x+"px";
                image.style.top = y+"px";
                image.style.display = '';

            };
            imageElem.style.display = 'none';
            imageElems.push(imageElem);
        }

        var currentImage = 0;
        var showImage = function (idx) {
            ret.innerHTML = "";
            if (imageElems[idx]) {
                ret.appendChild(imageElems[idx]);
                currentImage = idx;
            }
        };
        var showNextImage = function () {
            var newImage = currentImage + 1;
            if (! imageElems[newImage]) newImage = 0;
            showImage(newImage);
        };

        showImage(0);
        ret.addEventListener("click", showNextImage, true);
        
        return ret;
    }

    var doneonload = false;
    window.onload = document.onload = function () {
        if (doneonload) return;
        initialize();
        doneonload = true;
    }

})();


